package com.friddle.ocr.UUOcr;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

import com.friddle.ocr.OcrParse;

/**
 * Created by friddle on 15-1-29.
 */
public class UUOcr implements OcrParse {
	UuApi mUuApi;
	private static String appid = "103356";
	private static String appkey = "e3b996e00e774fd8918e6821b3f68284";

	public static void main(String[] args) {
		UUOcr mOcr = new UUOcr();
		String captch = mOcr.parseCaptch("./pic/taobao.jpeg");
		System.out.println(captch);
	}

	/**
	 * <p>
	 * if you use UuCloud to parse the Something,env must contain user and
	 * password of your uucloud account
	 * </p>
	 * <p>
	 * 假如你用悠悠云进行Ocr解析，那么Env必须包含有悠悠云的账号和密码
	 * </p>
	 * 
	 * @param envs
	 *            <table>
	 *            <td>username</td>
	 *            <td>用户账号</td>
	 *            <tr>
	 *            <td>passwd</td>
	 *            <td>用户密码</td>
	 *            <tr>
	 *            </table>
	 * @return
	 */
	@Override
	public MutablePair<Boolean, String> initEnviroment(Map<String, String> envs) {
		MutablePair<Boolean, String> result = new MutablePair<>();
		mUuApi = new UuApi();
		mUuApi.setSoftInfo(appid, appkey);
		String password = envs.get("password");
		String username = envs.get("username");
		String uuinfo = mUuApi.userLogin(username, password);
		if (uuinfo.equals("1")) {
		} else {
		}
		return result;
	}

	public static UUOcr ocr;

	public static UUOcr getOcrInstance() {
		if (ocr == null) {
			ocr = new UUOcr();
		}
		return ocr;
	}

	public String parseCaptch(String filename) {
		try {
			File downloadfile = new File(filename);
			String uid = mUuApi.upload(downloadfile.getAbsolutePath(), "1004", false);
			String phonenumber = mUuApi.getResult(uid);
			while (phonenumber.equals("")) {
				System.out.println(phonenumber);
				mUuApi.reportError(uid);
				Thread.sleep(1000);
				phonenumber = mUuApi.getResult(uid);
			}
			return phonenumber;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public void checkFiles(String filename) throws IOException {
		File targetFile = new File(filename);
		File pathfile = new File(targetFile.getParent());
		if (!pathfile.exists()) {
			if (!pathfile.exists()) {
				pathfile.mkdir();
			}
			if (!targetFile.exists()) {
				targetFile.createNewFile();
			}
		}
	}

	private synchronized File downloadFiles(String filename, String url) throws IOException {
		HttpGet mGet = new HttpGet(url);
		HttpResponse mResponse = HttpClientBuilder.create().build().execute(mGet);
		HttpEntity entity = mResponse.getEntity();
		File targetFile = new File(filename);
		if (entity != null) {
			InputStream inputStream = entity.getContent();
			OutputStream outputStream = new FileOutputStream(targetFile);
			IOUtils.copy(inputStream, outputStream);
			outputStream.close();
		}
		return targetFile;
	}

	@Override
	public Map.Entry<Integer, String> parseImages(File images, String types) {
		MutablePair<Integer, String> result = new MutablePair<Integer, String>();
		try {
			String uidstr = mUuApi.upload(images.getAbsolutePath(), types, false);
			Integer uid = Integer.valueOf(uidstr);
			String value = mUuApi.getResult(String.valueOf(uid));
			result.setLeft(uid);
			result.setRight(value);
			return result;
		} catch (Exception e) {
			result.setLeft(-1);
			result.setRight(e.getMessage());
			e.printStackTrace();
			return result;
		}
	}

	@Override
	public Map.Entry<Integer, String> parseUrls(String urls, String types) {
		MutablePair<Integer, String> mResult = new MutablePair<Integer, String>();
		try {
			String file = "./tmp/downloadfile";
			checkFiles(file);
			File downloadfile = this.downloadFiles(file, urls);
			String uidstr = mUuApi.upload(downloadfile.getAbsolutePath(), types, false);
			Integer uid = Integer.valueOf(uidstr);
			String value = mUuApi.getResult(String.valueOf(uid));
			mResult.setLeft(uid);
			mResult.setRight(value);
			return mResult;
		} catch (IOException e) {
			mResult.setLeft(-1);
			mResult.setRight(e.getMessage());
			e.printStackTrace();
		}
		return mResult;
	}

	@Override
	public void reportError(Integer id) {
		mUuApi.reportError(String.valueOf(id));
	}
}
